import React, { useState, useRef, useLayoutEffect } from 'react';
import { GridContent } from '@ant-design/pro-layout';
import { Card, Col, Menu, Row } from 'antd';
import SecurityView from './components/security';
import styles from './Center.less';
import { Avatar, Divider, Input, Tag } from 'antd';
import { CurrentUser, TagType } from '@/pages/account/center/data';
import {
  ClusterOutlined,
  ContactsOutlined,
  HomeOutlined, PlusOutlined
} from '@ant-design/icons';
import { connect } from 'umi';

const { Item } = Menu;

type SettingsStateKeys = 'base' | 'security' | 'binding';
type SettingsState = {
  mode: 'inline' | 'horizontal';
  selectKey: SettingsStateKeys;
};
const TagList: React.FC<{ tags: CurrentUser['tags'] }> = ({ tags }) => {
  const ref = useRef<Input | null>(null);
  const [newTags, setNewTags] = useState<TagType[]>([]);
  const [inputVisible, setInputVisible] = useState<boolean>(false);
  const [inputValue, setInputValue] = useState<string>('');

  const showInput = () => {
    setInputVisible(true);
    if (ref.current) {
      // eslint-disable-next-line no-unused-expressions
      ref.current?.focus();
    }
  };

  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    setInputValue(e.target.value);
  };

  const handleInputConfirm = () => {
    let tempsTags = [...newTags];
    if (inputValue && tempsTags.filter((tag) => tag.label === inputValue).length === 0) {
      tempsTags = [...tempsTags, { key: `new-${tempsTags.length}`, label: inputValue }];
    }
    setNewTags(tempsTags);
    setInputVisible(false);
    setInputValue('');
  };

  return (
    <div className={styles.tags}>
      <div className={styles.tagsTitle}>标签</div>
      {(tags || []).concat(newTags).map((item) => (
        <Tag key={item.key}>{item.label}</Tag>
      ))}
      {inputVisible && (
        <Input
          ref={ref}
          type="text"
          size="small"
          style={{ width: 78 }}
          value={inputValue}
          onChange={handleInputChange}
          onBlur={handleInputConfirm}
          onPressEnter={handleInputConfirm}
        />
      )}
      {!inputVisible && (
        <Tag onClick={showInput} style={{ borderStyle: 'dashed' }}>
          <PlusOutlined />
        </Tag>
      )}
    </div>
  );
};

const Settings: React.FC = (props) => {
  const userInfo = props.login.userInfo[0]?props.login.userInfo[0]:{
    userAccount: "",
    userName: "",
    avatar: "",
    sex: '',
    email: '',
    phoneNumber: '',
    roleLabel: "本科生"
  }
  console.log(props)
  console.log(userInfo)
  // 当前用户信息
  const currentUser = {
    name: localStorage.getItem("userName"),
    avatar: '/api/freshSystem/downloadFile/'+localStorage.getItem("avatar"),
    userid: localStorage.getItem("userAccount"),
    email: localStorage.getItem("email"),
    title: localStorage.getItem("roleLabel"),
    group: "电气工程学院",
    signature: '电气学子，探索未来',
    tags: [
      {
        key: '0',
        label: '很有想法的',
      },
      {
        key: '1',
        label: '乐观',
      },
      {
        key: '2',
        label: '勇敢',
      },
      {
        key: '3',
        label: '积极',
      },
      {
        key: '4',
        label: '阳光',
      },
      {
        key: '5',
        label: '有担当',
      },
    ],
    notice: [
      {
        id: 'xx01',
        title: "河北工业大学官网",
        logo: '',
        description: '河北工业大学始建于1903年，前身源于北洋工艺学堂，是河北省唯一一所211高校。' ,
        updatedAt: new Date(),
        member: '河北工业大学官网',
        href: 'https://www.hebut.edu.cn/',
        memberLink: '',
      },
      {
        id: 'xx02',
        title: "电气工程学院官网",
        logo: '',
        description: '电气工程学院有90年的发展历史，起源于1929年设立的机电工程系。' ,
        updatedAt: new Date(),
        member: '电气工程学院',
        href: 'https://ee.hebut.edu.cn/',
        memberLink: '',
      },
      {
        id: 'xxx1',
        title: 'IEEE Xplore Digital Library',
        logo: '',
        description: 'IEEE（电气和电子工程师学会）的数字图书馆，提供大量的学术文章和研究论文。' ,
        updatedAt: new Date(),
        member: 'IEEE Xplore Digital Library',
        href: 'https://ieeexplore.ieee.org/Xplore/home.jsp',
        memberLink: '',
      },
      {
        id: 'xxx2',
        title: "Bilibili",
        logo: '',
        description: 'B站学习区',
        updatedAt: new Date('2017-07-24'),
        member: 'Bilibili',
        href: 'https://www.bilibili.com/',
        memberLink: '',
      },
      {
        id: 'xxx3',
        title: "中国大学MOOC",
        logo: '',
        description: '中国大学MOOC',
        updatedAt: new Date(),
        member: '中国大学MOOC',
        href: 'https://www.icourse163.org/',
        memberLink: '',
      },
      {
        id: 'xxx4',
        title: "CSDN",
        logo: '',
        description: 'CSDN',
        updatedAt: new Date(),
        member: 'CSDN',
        href: 'https://www.csdn.net/',
        memberLink: '',
      },
      {
        id: 'xxx5',
        title: "ProcessOn",
        logo: '',
        description: '免费在线流程图思维导图',
        updatedAt: new Date(),
        member: 'ProcessOn',
        href: 'https://www.processon.com/',
        memberLink: '',
      }
    ],
    country: 'China',
    address: '',
    phone: '',
  };
  //  渲染用户信息
  const renderUserInfo = ({ title, group, geographic }: Partial<CurrentUser>) => {
    return (
      <div className={styles.detail}>
        <p>
          <ContactsOutlined
            style={{
              marginRight: 8,
            }}
          />
          {title}
        </p>
        <p>
          <ClusterOutlined
            style={{
              marginRight: 8,
            }}
          />
          {group}
        </p>
      </div>
    );
  };
  return (
    <GridContent>
      <Row gutter={24}>
        <Col lg={7} md={24}>
          <Card bordered={false} style={{ marginBottom: 24 }}>
            { currentUser && (
              <div>
                <div className={styles.avatarHolder}>
                  <img alt="" src={currentUser.avatar} />
                  <div className={styles.name}>{currentUser.name}</div>
                  <div>{currentUser?.signature}</div>
                </div>
                {renderUserInfo(currentUser)}
                <Divider dashed />
                <TagList tags={currentUser.tags || []} />
                <Divider style={{ marginTop: 16 }} dashed />
                <div className={styles.team}>
                  <div className={styles.teamTitle}>实用工具</div>
                  <Row gutter={36}>
                    {currentUser.notice &&
                      currentUser.notice.map((item) => (
                        <Col key={item.id} lg={24} xl={12}>
                          <a href={item.href} target="_blank" rel="noreferrer">
                            <Avatar size="small" src={item.logo} />
                            {item.member}
                          </a>
                        </Col>
                      ))}
                  </Row>
                </div>
              </div>
            )}
          </Card>
        </Col>
        <Col lg={17} md={24}>
          <Card
            className={styles.tabsCard}
            bordered={false}
          >
            <SecurityView />
          </Card>
        </Col>
      </Row>
    </GridContent>
  );
};
export default connect(({ login }: any) => ({
  login,
}))(Settings);
